package sys

import ("encoding/json"
	"git.oschina.net/YPTArch/apigateway/model"
	"github.com/johnhjwsosd/redis-operation/redisoper"
	"git.oschina.net/YPTArch/apigateway/lib"
	"git.oschina.net/YPTArch/apigateway/conf"
)
func getRedisData(key string) (interface{}, error) {
	hostString := conf.RedisHost()+":"+conf.RedisPort()
	authString := conf.RedisAuth()
	redis := redisoper.NewRedis(hostString, authString)
	res, err := redis.Smembers(key)
	return res, err
}



func getMS(msName string) *model.MsInfo {
	res, err := getRedisData("MS:" + msName)
	if err != nil {
		lib.HandleError("sys","getMS",err)
		return nil
	}
	ms := &model.MsInfo{}
	resList := res.([]string)
	if len(resList) != 0 {
		err = json.Unmarshal([]byte(resList[0]), ms)
	}
	return ms
}

func GetMsInfo(msName, apiName string) *model.RequestModel {
	msModel := getMS(msName)
	if msModel == nil {
		return nil
	}
	res, err := getRedisData("API:" + msName)
	if err != nil {
		lib.HandleError("sys","GetMsInfo",err)
		return nil
	}
	resList := res.([]string)
	result := &model.RequestModel{MsName: msName, MSHost: msModel.Host, APIName: apiName}
	for _, v := range resList {
		api := &model.APIInfo{}
		err := json.Unmarshal([]byte(v), api)
		if err != nil {
			lib.HandleError("sys","GetMsInfo", err)
			return nil
		}
		if api.APIName == apiName {
			result.APIMethods = api.APIMethods
			result.TokenMethods = api.TokenMethods
		}
	}
	return result
}